<template>
  <div class="ai-assistant">
    <SideNav />
    <div class="main-content">
      <!-- 分析按钮区域 -->
      <div class="action-buttons">
        <div class="button-group">
          <h3>学习分析</h3>
          <div class="buttons">
            <button class="action-btn" @click="analyzePattern" :disabled="isAnalyzing">
              <i class="fas fa-sitemap"></i>
              <span>解题模式分析</span>
            </button>
            <button class="action-btn" @click="analyzeWeakness" :disabled="isAnalyzing">
              <i class="fas fa-exclamation-circle"></i>
              <span>薄弱环节分析</span>
            </button>
            <button class="action-btn" @click="analyzeProgress" :disabled="isAnalyzing">
              <i class="fas fa-chart-line"></i>
              <span>学习进度分析</span>
            </button>
          </div>
        </div>
        <div class="button-group">
          <h3>提升建议</h3>
          <div class="buttons">
            <button class="action-btn" @click="generateLearningPath" :disabled="isAnalyzing">
              <i class="fas fa-road"></i>
              <span>个性化学习路径</span>
            </button>
            <button class="action-btn" @click="generateSkillImprovement" :disabled="isAnalyzing">
              <i class="fas fa-graduation-cap"></i>
              <span>能力提升建议</span>
            </button>
            <button class="action-btn" @click="generateCompetitionPrep" :disabled="isAnalyzing">
              <i class="fas fa-trophy"></i>
              <span>竞赛准备建议</span>
            </button>
            <button class="action-btn test-btn" @click="testAnalysisDisplay" :disabled="isAnalyzing">
              <i class="fas fa-vial"></i>
              <span>测试显示</span>
            </button>
          </div>
        </div>
      </div>

      <div class="content-container">
        <!-- 上部：分析结果展示 -->
        <div class="advice-section">
          <div class="section-card advice-card">
            <h2><i class="fas fa-comment-dots"></i> AI 建议</h2>
            <div v-if="currentAnalysis" class="analysis-content">
              <!-- 解析后的内容展示 -->
              <div v-if="parsedAnalysis" class="parsed-content">
                <div class="summary-box">
                  <h3><i class="fas fa-chart-line"></i> 学习概要</h3>
                  <p>{{ parsedAnalysis.summary }}</p>
                </div>
                
                <div class="advice-list">
                  <div v-for="(advice, index) in parsedAnalysis.advices" :key="index" class="advice-item">
                    <div :class="['advice-icon', advice.type]">
                      <i :class="['fas', advice.icon || getDefaultIcon(advice.type)]"></i>
                    </div>
                    <div class="advice-content">
                      <h4>{{ advice.title }}</h4>
                      <div v-html="formatAdviceContent(advice.content)" class="advice-text"></div>
                    </div>
                  </div>
                </div>
              </div>
              
              <!-- 原始响应显示（如解析失败） -->
              <div v-else class="raw-response">
                <pre>{{ currentAnalysis.raw_response }}</pre>
              </div>
            </div>
            <div class="loading-container" v-else-if="isAnalyzing">
              <div class="loading-spinner"></div>
              <p>AI正在分析您的数据...</p>
            </div>
            <div class="empty-state" v-else>
              <p>点击上方按钮获取AI分析和建议</p>
            </div>
          </div>
        </div>

        <!-- 下部：AI对话区域 -->
        <div class="chat-section">
          <h2><i class="fas fa-robot"></i> AI助手对话</h2>
          <div class="chat-container">
            <div class="chat-messages" ref="chatMessages">
              <div v-for="(message, index) in chatHistory" :key="index" :class="'message ' + message.role">
                <div class="message-content" v-html="formatMessage(message.content)"></div>
              </div>
              <div class="message assistant typing" v-if="isTyping">
                <div class="typing-indicator">
                  <span></span>
                  <span></span>
                  <span></span>
                </div>
              </div>
            </div>
            <div class="chat-input">
              <textarea 
                v-model="userInput" 
                placeholder="向AI助手提问..." 
                @keydown.enter.prevent="sendMessage"
                :disabled="isTyping"
                rows="2"
              ></textarea>
              <button @click="sendMessage" :disabled="!userInput.trim() || isTyping">
                <i class="fas fa-paper-plane"></i>
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import SideNav from '@/components/SideNav.vue'
import { marked } from 'marked'
import axios from 'axios'
import { baseURL } from '@/utils/api'

export default {
  name: 'AIAssistantView',
  components: {
    SideNav
  },
  data() {
    return {
      // 题目统计数据
      problemStats: {
        totalCount: 0,
        difficultyStats: {
          EASY: 0,
          MEDIUM: 0,
          HARD: 0
        }
      },
      // 难度分布数据
      difficultyData: {
        solved: { easy: 0, medium: 0, hard: 0 },
        total: { easy: 0, medium: 0, hard: 0 }
      },
      // 用户活动历史
      activityData: [],
      // 分析状态
      isAnalyzing: false,
      currentAnalysis: null,
      // 聊天相关
      chatHistory: [],
      userInput: "",
      isTyping: false,
      // 用户ID
      userId: null,
      parsedAnalysis: null
    };
  },
  mounted() {
    // 获取用户ID（从localStorage或者vuex中）
    this.userId = localStorage.getItem('userId') || 5567282326400; // 使用数据库中的有效用户ID作为默认值
    console.log('初始化AIAssistant组件，用户ID:', this.userId);
    
    // 页面加载时获取数据
    this.fetchProblemStats();
    this.fetchActivityHistory();
    
    // 初始化AI助手问候语
    this.chatHistory.push({
      role: 'assistant',
      content: '你好！我是你的AI学习助手。有任何刷题、学习问题都可以问我。'
    });
  },
  methods: {
    // 数据获取方法
    async fetchProblemStats() {
      try {
        // 获取题目统计数据
        const response = await axios({
          method: 'get',
          url: baseURL + `/CodeQuestion-service/problems/getProblemStats`
        });
        
        if (response.data.code === 200) {
          this.problemStats = response.data.data;
          console.log('题目统计数据:', this.problemStats);
          
          // 设置难度分布数据
          this.difficultyData.total = {
            easy: this.problemStats.difficultyStats?.EASY || 0,
            medium: this.problemStats.difficultyStats?.MEDIUM || 0,
            hard: this.problemStats.difficultyStats?.HARD || 0
          };
          console.log('总题目难度分布:', this.difficultyData.total);
          
          // 获取用户已解决的题目难度统计
          const userDifficultyResponse = await axios({
            method: 'get',
            url: baseURL + `/CodeQuestion-service/problems/getUserDifficultyStats/${this.userId}`
          });
          
          console.log('用户难度统计原始响应:', userDifficultyResponse.data);
          
          if (userDifficultyResponse.data.code === 200) {
            // 处理后端返回的数据
            const userDifficultyStats = userDifficultyResponse.data.data || [];
            
            // 初始化默认值
            const solvedStats = {
              easy: 0,
              medium: 0,
              hard: 0
            };
            
            // 遍历后端数据进行转换
            userDifficultyStats.forEach(item => {
              if (item.difficulty) {
                const difficulty = item.difficulty.toLowerCase();
                if (difficulty === 'easy') solvedStats.easy = item.count || 0;
                else if (difficulty === 'medium') solvedStats.medium = item.count || 0;
                else if (difficulty === 'hard') solvedStats.hard = item.count || 0;
              }
            });
            
            this.difficultyData.solved = solvedStats;
            console.log('用户解题难度分布:', this.difficultyData.solved);
          }
        }
      } catch (error) {
        console.error('获取题目统计数据失败:', error);
      }
    },
    
    async fetchActivityHistory() {
      try {
        const response = await axios({
          method: 'get',
          url: baseURL + `/CodeQuestion-service/problems/getUserActivityHistory/${this.userId}`
        });
        
        console.log('用户活动历史原始响应:', response.data);
        
        if (response.data.code === 200) {
          // 确保数据有效，返回格式为[{date:'2023-04-05', count:4}, ...]
          this.activityData = response.data.data || [];
          console.log('处理后的用户活动历史:', this.activityData);
          
          // 如果后端返回的格式不同，进行转换
          if (this.activityData.length > 0 && (typeof this.activityData[0].date === 'undefined')) {
            this.activityData = this.activityData.map(item => {
              return {
                date: item.activityDate || item.date,
                count: item.activityCount || item.count || 0
              };
            });
            console.log('转换后的用户活动历史:', this.activityData);
          }
        }
      } catch (error) {
        console.error('获取活动历史数据失败:', error);
      }
    },
    
    // 分析触发方法
    async analyzePattern() {
      console.log('开始解题模式分析，用户ID:', this.userId);
      this.startAnalysis();
      try {
        console.log('发送解题模式分析请求:', `${baseURL}/ai-service/AI/analyze-pattern?userId=${this.userId}`);
        const response = await axios({
          method: 'get',
          url: baseURL + `/ai-service/AI/analyze-pattern?userId=${this.userId}`
        });
        
        console.log('解题模式分析原始响应:', response);
        console.log('解题模式分析响应数据:', response.data);
        
        // 设置原始响应
        this.currentAnalysis = response.data;
        
        // 检查响应结构
        if (response.data && response.data.raw_response) {
          // 后端返回了包装的响应
          this.parseAIResponse(response.data.raw_response);
        } else if (response.data && (response.data.summary || response.data.advices)) {
          // 后端直接返回了JSON对象
          this.parsedAnalysis = response.data;
          console.log('直接使用后端返回的JSON对象:', this.parsedAnalysis);
        } else {
          // 尝试解析整个响应
          this.parseAIResponse(response.data);
        }
        
        this.endAnalysis();
      } catch (error) {
        console.error('解题模式分析失败:', error);
        this.endAnalysis();
      }
    },
    
    async analyzeWeakness() {
      console.log('开始薄弱环节分析，用户ID:', this.userId);
      this.startAnalysis();
      try {
        console.log('发送薄弱环节分析请求:', `${baseURL}/ai-service/AI/analyze-weakness?userId=${this.userId}`);
        const response = await axios({
          method: 'get',
          url: baseURL + `/ai-service/AI/analyze-weakness?userId=${this.userId}`
        });
        
        console.log('薄弱环节分析响应数据:', response.data);
        
        // 设置原始响应
        this.currentAnalysis = response.data;
        
        // 检查响应结构
        if (response.data && response.data.raw_response) {
          // 后端返回了包装的响应
          this.parseAIResponse(response.data.raw_response);
        } else if (response.data && (response.data.summary || response.data.advices)) {
          // 后端直接返回了JSON对象
          this.parsedAnalysis = response.data;
          console.log('直接使用后端返回的JSON对象:', this.parsedAnalysis);
        } else {
          // 尝试解析整个响应
          this.parseAIResponse(response.data);
        }
        
        this.endAnalysis();
      } catch (error) {
        console.error('薄弱环节分析失败:', error);
        this.endAnalysis();
      }
    },
    
    async analyzeProgress() {
      console.log('开始学习进度分析，用户ID:', this.userId);
      this.startAnalysis();
      try {
        console.log('发送学习进度分析请求:', `${baseURL}/ai-service/AI/analyze-progress?userId=${this.userId}`);
        const response = await axios({
          method: 'get',
          url: baseURL + `/ai-service/AI/analyze-progress?userId=${this.userId}`
        });
        
        console.log('学习进度分析响应数据:', response.data);
        
        // 设置原始响应
        this.currentAnalysis = response.data;
        
        // 检查响应结构
        if (response.data && response.data.raw_response) {
          // 后端返回了包装的响应
          this.parseAIResponse(response.data.raw_response);
        } else if (response.data && (response.data.summary || response.data.advices)) {
          // 后端直接返回了JSON对象
          this.parsedAnalysis = response.data;
          console.log('直接使用后端返回的JSON对象:', this.parsedAnalysis);
        } else {
          // 尝试解析整个响应
          this.parseAIResponse(response.data);
        }
        
        this.endAnalysis();
      } catch (error) {
        console.error('学习进度分析失败:', error);
        this.endAnalysis();
      }
    },
    
    async generateLearningPath() {
      console.log('开始生成学习路径，用户ID:', this.userId);
      this.startAnalysis();
      try {
        console.log('发送学习路径请求:', `${baseURL}/ai-service/AI/learning-path?userId=${this.userId}`);
        const response = await axios({
          method: 'get',
          url: baseURL + `/ai-service/AI/learning-path?userId=${this.userId}`
        });
        
        console.log('学习路径响应数据:', response.data);
        
        // 设置原始响应
        this.currentAnalysis = response.data;
        
        // 检查响应结构
        if (response.data && response.data.raw_response) {
          // 后端返回了包装的响应
          this.parseAIResponse(response.data.raw_response);
        } else if (response.data && (response.data.summary || response.data.advices)) {
          // 后端直接返回了JSON对象
          this.parsedAnalysis = response.data;
          console.log('直接使用后端返回的JSON对象:', this.parsedAnalysis);
        } else {
          // 尝试解析整个响应
          this.parseAIResponse(response.data);
        }
        
        this.endAnalysis();
      } catch (error) {
        console.error('个性化学习路径生成失败:', error);
        this.endAnalysis();
      }
    },
    
    async generateSkillImprovement() {
      console.log('开始生成能力提升建议，用户ID:', this.userId);
      this.startAnalysis();
      try {
        console.log('发送能力提升建议请求:', `${baseURL}/ai-service/AI/skill-improvement?userId=${this.userId}`);
        const response = await axios({
          method: 'get',
          url: baseURL + `/ai-service/AI/skill-improvement?userId=${this.userId}`
        });
        
        console.log('能力提升建议响应数据:', response.data);
        
        // 设置原始响应
        this.currentAnalysis = response.data;
        
        // 检查响应结构
        if (response.data && response.data.raw_response) {
          // 后端返回了包装的响应
          this.parseAIResponse(response.data.raw_response);
        } else if (response.data && (response.data.summary || response.data.advices)) {
          // 后端直接返回了JSON对象
          this.parsedAnalysis = response.data;
          console.log('直接使用后端返回的JSON对象:', this.parsedAnalysis);
        } else {
          // 尝试解析整个响应
          this.parseAIResponse(response.data);
        }
        
        this.endAnalysis();
      } catch (error) {
        console.error('能力提升建议生成失败:', error);
        this.endAnalysis();
      }
    },
    
    async generateCompetitionPrep() {
      console.log('开始生成竞赛准备建议，用户ID:', this.userId);
      this.startAnalysis();
      try {
        console.log('发送竞赛准备建议请求:', `${baseURL}/ai-service/AI/competition-prep?userId=${this.userId}`);
        const response = await axios({
          method: 'get',
          url: baseURL + `/ai-service/AI/competition-prep?userId=${this.userId}`
        });
        
        console.log('竞赛准备建议响应数据:', response.data);
        
        // 设置原始响应
        this.currentAnalysis = response.data;
        
        // 检查响应结构
        if (response.data && response.data.raw_response) {
          // 后端返回了包装的响应
          this.parseAIResponse(response.data.raw_response);
        } else if (response.data && (response.data.summary || response.data.advices)) {
          // 后端直接返回了JSON对象
          this.parsedAnalysis = response.data;
          console.log('直接使用后端返回的JSON对象:', this.parsedAnalysis);
        } else {
          // 尝试解析整个响应
          this.parseAIResponse(response.data);
        }
        
        this.endAnalysis();
      } catch (error) {
        console.error('竞赛准备建议生成失败:', error);
        this.endAnalysis();
      }
    },
    
    // AI对话方法
    async sendMessage() {
      if (!this.userInput.trim() || this.isTyping) return;
      
      const userMessage = this.userInput.trim();
      this.chatHistory.push({ role: 'user', content: userMessage });
      this.userInput = '';
      this.isTyping = true;
      
      // 滚动到底部
      this.$nextTick(() => {
        if (this.$refs.chatMessages) {
          this.$refs.chatMessages.scrollTop = this.$refs.chatMessages.scrollHeight;
        }
      });
      
      try {
        // 调用流式对话API
        const source = new EventSource(
          `${baseURL}/ai-service/AI/stream-chat?question=${encodeURIComponent(userMessage)}`
        );
        
        let aiResponse = '';
        
        source.onmessage = (event) => {
          if (event.data === '[DONE]') {
            source.close();
            this.isTyping = false;
            return;
          }
          
          aiResponse += event.data;
          
          // 更新聊天历史
          if (this.chatHistory[this.chatHistory.length - 1].role === 'assistant') {
            this.chatHistory[this.chatHistory.length - 1].content = aiResponse;
          } else {
            this.chatHistory.push({ role: 'assistant', content: aiResponse });
          }
          
          // 滚动到底部
          this.$nextTick(() => {
            if (this.$refs.chatMessages) {
              this.$refs.chatMessages.scrollTop = this.$refs.chatMessages.scrollHeight;
            }
          });
        };
        
        source.onerror = (error) => {
          console.error('流式对话请求失败:', error);
          source.close();
          this.isTyping = false;
          
          if (!aiResponse) {
            this.chatHistory.push({ 
              role: 'assistant', 
              content: '抱歉，我遇到了一些问题，请稍后再试。' 
            });
          }
        };
      } catch (error) {
        console.error('发送消息失败:', error);
        this.isTyping = false;
        this.chatHistory.push({ 
          role: 'assistant', 
          content: '抱歉，我遇到了一些问题，请稍后再试。' 
        });
      }
    },
    
    // 辅助方法
    startAnalysis() {
      console.log('开始分析状态设置为true');
      this.isAnalyzing = true;
      this.currentAnalysis = null;
      this.parsedAnalysis = null;
    },
    
    endAnalysis() {
      console.log('结束分析状态设置为false');
      this.isAnalyzing = false;
    },
    
    formatMessage(content) {
      // 使用markdown渲染消息内容
      return marked(content);
    },
    
    formatAdviceContent(content) {
      // 使用markdown渲染建议内容
      return marked(content);
    },
    
    parseAIResponse(rawResponse) {
      try {
        console.log('尝试解析AI响应数据:', rawResponse);
        
        // 如果rawResponse为空，直接返回
        if (!rawResponse) {
          console.error('AI响应数据为空');
          this.parsedAnalysis = null;
          return;
        }
        
        // 如果已经是对象，直接使用
        if (typeof rawResponse === 'object' && rawResponse !== null) {
          console.log('AI响应已经是对象:', rawResponse);
          this.parsedAnalysis = rawResponse;
          return;
        }
        
        // 确保rawResponse是字符串
        if (typeof rawResponse !== 'string') {
          console.error('AI响应数据不是字符串:', typeof rawResponse);
          this.parsedAnalysis = null;
          return;
        }
        
        // 尝试解析JSON字符串
        const parsed = JSON.parse(rawResponse.trim());
        console.log('成功解析JSON数据:', parsed);
        
        if (parsed && (parsed.summary || parsed.advices)) {
          this.parsedAnalysis = parsed;
          console.log('设置解析后的数据:', this.parsedAnalysis);
        } else {
          console.error('解析后的数据缺少必要字段:', parsed);
          this.parsedAnalysis = null;
        }
      } catch (error) {
        console.error('解析AI响应失败:', error, '原始数据:', rawResponse);
        
        // 尝试用正则表达式匹配JSON部分
        try {
          const jsonMatch = rawResponse.match(/\{[\s\S]*\}/);
          if (jsonMatch) {
            console.log('尝试提取JSON部分:', jsonMatch[0]);
            const extractedJson = JSON.parse(jsonMatch[0]);
            if (extractedJson && (extractedJson.summary || extractedJson.advices)) {
              this.parsedAnalysis = extractedJson;
              console.log('成功提取JSON数据:', this.parsedAnalysis);
              return;
            }
          }
        } catch (extractError) {
          console.error('提取JSON失败:', extractError);
        }
        
        this.parsedAnalysis = null;
      }
    },
    
    getDefaultIcon(type) {
      // 根据建议类型返回默认图标
      switch(type) {
        case 'warning':
          return 'fa-exclamation-triangle';
        case 'success':
          return 'fa-check-circle';
        case 'info':
          return 'fa-info-circle';
        default:
          return 'fa-lightbulb';
      }
    },
    
    // 测试方法 - 用于模拟API响应
    testAnalysisDisplay() {
      console.log('测试AI分析显示');
      
      // 基于数据库实际数据创建模拟数据
      const mockData = {
        "summary": "用户目前总共解决了2道题目，均为简单难度。最近两次刷题活动分别在2025年3月19日（4题）和2025年3月13日（5题），显示出一定的刷题频率。",
        "advices": [
          {
            "title": "建立每日刷题习惯",
            "content": "检测到您的刷题间隔为6天（3月13日→3月19日），建议设定每日固定时间练习，保持连续性。可以从每天1题开始逐步增加。",
            "type": "warning",
            "icon": "fa-calendar-check"
          },
          {
            "title": "尝试中等难度题目",
            "content": "目前您只解决了简单难度题目，建议逐步尝试中等难度题目，提升自己的解题能力。",
            "type": "info",
            "icon": "fa-signal-bars-weak"
          },
          {
            "title": "记录解题过程",
            "content": "建议记录每道题的解题思路，包括：1）思考过程 2）遇到的难点 3）优化方向。这样有助于复习和加深理解。",
            "type": "success",
            "icon": "fa-clipboard-list"
          },
          {
            "title": "多样化编程语言",
            "content": "尝试使用不同的编程语言解决同一问题，可以加深对算法本质的理解，并提高不同语言的熟练度。",
            "type": "info",
            "icon": "fa-code"
          }
        ]
      };
      
      // 设置活动数据和难度数据，便于测试UI显示
      this.difficultyData.solved = {
        easy: 2,
        medium: 0,
        hard: 0
      };
      
      this.difficultyData.total = {
        easy: 100,
        medium: 150,
        hard: 50
      };
      
      this.activityData = [
        { date: "2025-03-19", count: 4 },
        { date: "2025-03-13", count: 5 }
      ];
      
      this.startAnalysis();
      
      // 直接应用模拟数据
      this.currentAnalysis = {
        code: 200,
        message: "操作成功",
        raw_response: JSON.stringify(mockData)
      };
      
      // 设置解析后的数据
      this.parsedAnalysis = mockData;
      
      this.endAnalysis();
      
      console.log('测试数据已加载:', this.parsedAnalysis);
    }
  }
}
</script>

<style scoped>
.ai-assistant {
  min-height: 100vh;
  background-color: #f0f7ff;
  display: flex;
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  margin-left: 60px;
  padding: 24px;
  gap: 20px;
  height: 100vh;
  max-width: 1400px;
  overflow-y: auto;
}

/* 按钮样式 */
.action-buttons {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 20px;
}

.button-group {
  background-color: white;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition: box-shadow 0.3s ease;
}

.button-group:hover {
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
}

.button-group h3 {
  margin-top: 0;
  margin-bottom: 15px;
  color: #333;
  font-size: 1.2rem;
}

.buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.action-btn {
  flex: 1;
  min-width: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 10px 15px;
  background-color: #f5f9ff;
  border: 1px solid #e1e8f0;
  border-radius: 8px;
  color: #4a6ee0;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
}

.action-btn:hover {
  background-color: #ebf3ff;
  transform: translateY(-2px);
}

.action-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
}

.action-btn i {
  font-size: 1rem;
}

/* 内容容器样式 */
.content-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
  flex: 1;
  min-height: 0;
  overflow: auto;
  height: 100%;
}

.advice-section {
  flex: 1;
  min-height: 250px;
  max-height: 45vh;
}

/* 卡片通用样式 */
.section-card {
  background-color: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  height: 100%;
}

.section-card h2 {
  margin-top: 0;
  margin-bottom: 15px;
  color: #333;
  font-size: 1.3rem;
  display: flex;
  align-items: center;
  gap: 8px;
}

.section-card h2 i {
  color: #4a6ee0;
}

/* 建议卡片样式 */
.advice-card {
  overflow-y: auto;
}

/* 加载状态 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 15px;
  height: 100%;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(74, 110, 224, 0.2);
  border-radius: 50%;
  border-top-color: #4a6ee0;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #888;
  font-style: italic;
}

/* 聊天部分样式 */
.chat-section {
  flex: 1 1 auto;
  background-color: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
  min-height: 300px;
  max-height: none;
  overflow: hidden;
}

.chat-section h2 {
  margin-top: 0;
  margin-bottom: 15px;
  color: #333;
  font-size: 1.3rem;
  display: flex;
  align-items: center;
  gap: 8px;
}

.chat-section h2 i {
  color: #4a6ee0;
}

.chat-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
  flex: 1;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
  display: flex;
  flex-direction: column;
  gap: 15px;
  min-height: 50px;
}

.message {
  max-width: 80%;
  padding: 12px 16px;
  border-radius: 12px;
  line-height: 1.5;
}

.message.user {
  align-self: flex-end;
  background-color: #4a6ee0;
  color: white;
  border-bottom-right-radius: 4px;
}

.message.assistant {
  align-self: flex-start;
  background-color: #f5f7fb;
  color: #333;
  border-bottom-left-radius: 4px;
}

.message-content {
  white-space: pre-wrap;
}

.message-content a {
  color: inherit;
  text-decoration: underline;
}

.typing-indicator {
  display: flex;
  align-items: center;
  gap: 3px;
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  background-color: #aaa;
  border-radius: 50%;
  animation: bounce 1.5s infinite;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes bounce {
  0%, 60%, 100% { transform: translateY(0); }
  30% { transform: translateY(-5px); }
}

.chat-input {
  display: flex;
  gap: 10px;
  padding: 15px 0 0 0;
  border-top: 1px solid #eee;
  margin-top: 10px;
}

.chat-input textarea {
  flex: 1;
  padding: 12px;
  border: 1px solid #e1e8f0;
  border-radius: 8px;
  resize: none;
  font-family: inherit;
  font-size: 0.95rem;
  transition: border-color 0.2s ease;
}

.chat-input textarea:focus {
  outline: none;
  border-color: #4a6ee0;
}

.chat-input button {
  padding: 0 15px;
  background-color: #4a6ee0;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.chat-input button:hover {
  background-color: #3a5ecc;
}

.chat-input button:disabled {
  background-color: #b3c2e8;
  cursor: not-allowed;
}

/* 响应式设计 */
@media (max-width: 992px) {
  .action-buttons {
    grid-template-columns: 1fr;
  }
  
  .main-content {
    margin-left: 0;
    padding: 16px;
    height: auto;
    min-height: 100vh;
  }
  
  .chat-section {
    max-height: none;
    min-height: 350px;
  }
}

/* 原始响应样式 */
.raw-response {
  white-space: pre-wrap;
  font-family: monospace;
  background-color: #f8f9fa;
  padding: 10px;
  border-radius: 4px;
  overflow-y: auto;
  max-height: 100%;
  font-size: 0.9rem;
}

.raw-response pre {
  margin: 0;
  color: #333;
  line-height: 1.5;
}

.analysis-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
  height: 100%;
  overflow-y: auto;
}

.parsed-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.summary-box {
  background-color: #f0f7ff;
  padding: 15px;
  border-radius: 8px;
  border-left: 4px solid #4a6ee0;
}

.summary-box h3 {
  margin-top: 0;
  margin-bottom: 10px;
  color: #333;
  font-size: 1.1rem;
  display: flex;
  align-items: center;
  gap: 8px;
}

.summary-box p {
  margin: 0;
  color: #555;
  line-height: 1.5;
}

.advice-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.advice-item {
  display: flex;
  gap: 15px;
  background-color: #f9fbff;
  border-radius: 8px;
  padding: 15px;
  border-left: 4px solid #4a6ee0;
}

.advice-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #e3eaff;
  color: #4a6ee0;
  flex-shrink: 0;
}

.advice-icon.warning {
  background-color: #fff3e0;
  color: #ff9800;
}

.advice-icon.success {
  background-color: #e8f5e9;
  color: #4caf50;
}

.advice-icon.info {
  background-color: #e3f2fd;
  color: #2196f3;
}

.advice-content {
  flex: 1;
}

.advice-content h4 {
  margin-top: 0;
  margin-bottom: 8px;
  color: #333;
  font-size: 1rem;
}

.advice-content p {
  margin: 0;
  color: #555;
  line-height: 1.5;
  font-size: 0.9rem;
}

.test-btn {
  background-color: #f5f0ff;
  color: #8a6ee0;
}

.test-btn:hover {
  background-color: #ebe3ff;
}

.advice-text :deep(pre) {
  background-color: #f5f5f5;
  padding: 10px;
  border-radius: 4px;
  overflow-x: auto;
  font-size: 0.85rem;
  margin: 8px 0;
}

.advice-text :deep(code) {
  font-family: "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace;
  background-color: #f0f0f0;
  padding: 2px 4px;
  border-radius: 3px;
  font-size: 0.85em;
}

.advice-text :deep(p) {
  margin: 8px 0;
}
</style> 